from urllib import request
from urllib import parse
from config import config_common as config
from utils import logging
from classes import QyWxInfo, MsgType
from api import api_qywx_info as info
import sys, json, time
import logging

def get_weather_info(cityname):
    WEATHER_API_URL = config.WEATHER_API_URL
    WEATHER_API_URL = str(WEATHER_API_URL).replace("${key}", config.WEATHER_APP_KEY)
    WEATHER_API_URL = str(WEATHER_API_URL).replace("${cityname}", parse.quote(cityname))
    req = request.Request(WEATHER_API_URL)
    req.method = "GET"
    try:
        resp = request.urlopen(req)
    except request.HTTPError as e:
        logging.exception(e.msg, e.args)
        sys.exit(1)
    response_dictionary = json.load(resp)
    current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    data = "<div>"+current_time+"</div>"
    if response_dictionary["resultcode"] == "200":
        data += "<div class=\"normal\">" \
               + "温度:" + response_dictionary["result"]["sk"]["temp"] + "℃\n"\
               + "风力:" + response_dictionary["result"]["sk"]["wind_direction"] + ""\
               + response_dictionary["result"]["sk"]["wind_strength"] + "\n"\
               + "湿度:" + response_dictionary["result"]["sk"]["humidity"] + ""\
               + "</div>"\
               + "<div class=\"highlight\">" \
               + response_dictionary["result"]["today"]["dressing_advice"] \
               + "</div>"
        return data
    else:
        data = response_dictionary
        logging.error(response_dictionary)
        return data


def send_info():
    data = get_weather_info("天津")
    logging.info(data)
    info_object = QyWxInfo.QyWxInfo()
    info_object.touser = "@all"
    info_object.title = "实况天气"
    info_object.description = data
    info_object.url = "http://www.weather.com.cn/weather1d/101030100.shtml"
    info_object.msgtype = MsgType.MsgType.TEXTCARD.value
    info_object.agentid = "1000002"
    info_object.safe = 0
    info.send_weather_info(info_object)